package com.example.mycomposelearing.custom

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.lazy.staggeredgrid.rememberLazyStaggeredGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.*
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle

import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.mycomposelearing.ui.theme.MyComposeLearingTheme
import kotlinx.coroutines.launch
import java.lang.Math.max

/**
 *@Author tgw
 *@Date 2023/07/17
 *@describe
 */
class CustomMainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // A surface container using the 'background' color from the theme
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colorScheme.background
            ) {
                Greeting(name = "自定义view布局")
            }
        }
    }


    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    fun Greeting(name: String) {

        Box {

            // Remember our own LazyListState，响应滚动位置
            val listState = rememberLazyListState()
            val coroutineScope = rememberCoroutineScope()

            // 自定义viewgroup，横向流式布局
            val topics = listOf(
                "position1 谁发发发双法防谁发发发双法防谁发发发双法防",
                "position2 ",
                "position3 通天塔",
                "position4 哈哈哈哈哈哈",
                "position5 火花",
                "position6 ",
                "position7 灌灌灌灌",
                "position8 000",
                "position9 天啊啊啊",
                "position10 来来来",
                "position11 哦哦哦哦哦哦哦哦",
                "position12 前期去去去去去去去去去",
                "position13 与i一有意义有意义",
                "position14 iiiiiiiii",
                "position15 谁发发发双法防谁发发发双法防谁发发发双法防",
                "position16 呜呜呜呜呜呜",
                "position17 来了来了",
                "position18 啊啊啊",
                "position19 ",
            )
            LazyColumn(state = listState) {
                item {
                    Text(
                        text = "自定义的文本高度对齐",
                        modifier = Modifier.background(Color(0xFFC56565))
                    )
                    // 未自定义
                    NoCustomLayoutDemo()
                    // 自定义
                    CustomLayoutDemo()
                }
                stickyHeader {
                    Text(
                        text = "粘性头部，自定义的横向流式布局",
                        modifier = Modifier.background(Color(0xFFC56565))
                    )
                    Row(
                        modifier = Modifier
                            .horizontalScroll(rememberScrollState())
                            .animateItemPlacement(
                                tween(durationMillis = 250)
                            )
                    ) {
                        StaggeredGrid() {
                            for (topic in topics) {
                                Chip(
                                    modifier = Modifier
                                        .padding(8.dp)
                                        .clickable {
                                            Toast
                                                .makeText(
                                                    this@CustomMainActivity,
                                                    "显示：$topic",
                                                    Toast.LENGTH_SHORT
                                                )
                                                .show()
                                        }, text = topic
                                )
                            }
                        }
                    }


                }

                item {
                    Text(
                        text = "系统的滑动item布局",
                        modifier = Modifier.background(Color(0xFFC56565))
                    )

                    //竖向的流式布局,嵌套滑动的话LazyColumn得确定好高度，否则报错
//            ColumnStaggeredGrid(topics)
//            StaggeredGrid1(items = topics, numColumns = 2, modifier = Modifier
//                .weight(1f))
//            StaggeredGrid1(items = topics, numColumns = 2, modifier = Modifier
//                .weight(1f))
                    ColumnStaggeredGrid(topics)
                }

                item {
                    Text(
                        text = "自定义的竖向瀑布流布局",
                        modifier = Modifier.background(Color(0xFFC56565))
                    )
                    Column(
                        modifier = Modifier
//                    .verticalScroll(rememberScrollState())
                            .background(Color(0xFF00FF00))
                    ) {
                        CustomVerticalStaggeredGrid() {
                            for (topic in topics) {
                                Column {
                                    Text(text = topic, modifier = Modifier
                                        .clickable {
                                            Toast
                                                .makeText(
                                                    this@CustomMainActivity,
                                                    "显示：$topic",
                                                    Toast.LENGTH_SHORT
                                                )
                                                .show()
                                        }
                                        .background(Color(0xFFB88076))
                                        .padding(8.dp))
                                    Spacer(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .height(1.dp)
                                            .background(Color(0xFFFFFEFE))
                                    )
                                }

                            }
                        }
                    }
                }

                item {
                    AnnotatedClickableText("自定义的布局CustomIntrinsicRow 固有特性测量属性")
                    Text(
                        text = "自定义的布局CustomIntrinsicRow 固有特性测量属性",
                        modifier = Modifier.background(Color(0xFFC56565))
                    )
                    CustomIntrinsicRow(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(IntrinsicSize.Min)
                    ) {
                        Text(
                            text = "Left",
                            Modifier
                                .wrapContentWidth(Alignment.Start)
                                .layoutId("main")
                        )
                        Divider(
                            color = Color.Black,
                            modifier = Modifier
                                .width(4.dp)
                                .fillMaxHeight()
                                .layoutId("devider")
                        )
                        Text(
                            text = "Right",
                            Modifier
                                .wrapContentWidth(Alignment.End)
                                .background(Color(0xFFF8A3A3))
                                .layoutId("main")
                        )
                    }
                }


                stickyHeader {
                    Text(
                        text = "粘性头部，后面会挤掉前面的只保留一个",
                        modifier = Modifier.background(Color(0xFFC56565))
                    )
                }

                item {
                    Text(
                        text = "系统的瀑布流", modifier = Modifier
                            .background(Color(0xFFC56565))
                    )

                    // 存储所有item高度
                    val itemHeights = remember { mutableStateListOf<Int>() }

                    val lazyVerticalStaggeredGrid = rememberLazyStaggeredGridState()
                    val totalHeight by remember {
                        derivedStateOf {
                            lazyVerticalStaggeredGrid.layoutInfo.visibleItemsInfo.forEach {
                                Log.d("TAG", "lazyVerticalStaggeredGrid:${it.offset} ")
                            }
                        }
                    }
                    LazyVerticalStaggeredGrid(
                        state = lazyVerticalStaggeredGrid,
                        columns = StaggeredGridCells.Fixed(3),
                        modifier = Modifier.height(200.dp)
                    ) {
                        items(topics) { topic ->
                            Column (modifier = Modifier.onGloballyPositioned{
                                itemHeights.add(it.size.height)
                            }){
                                Text(text = topic, fontSize = 10.sp, modifier = Modifier
                                    .clickable {
                                        Toast
                                            .makeText(
                                                this@CustomMainActivity,
                                                "显示：$topic",
                                                Toast.LENGTH_SHORT
                                            )
                                            .show()
                                    }
                                    .background(Color(0xFFB88076))
                                    .padding(8.dp))
                                Spacer(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(1.dp)
                                        .background(Color(0xFF44CC44))
                                )
                            }

                        }

                    }

                }



                item {
                    Text(
                        text = "底部高度占位", modifier = Modifier
                            .background(Color(0xFFC56565))
                            .height(1000.dp)
                    )
                }
            }


            // Show the button if the first visible item is past
            // the first item. We use a remembered derived state to
            // minimize unnecessary compositions
            val showButton by remember {
                derivedStateOf {
                    listState.firstVisibleItemIndex > 1
                }
            }

            AnimatedVisibility(
                visible = showButton, modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .background(
                        Color(0xFFC56565)
                    )
            ) {
                TextButton(onClick = {
                    coroutineScope.launch {
                        listState.animateScrollToItem(index = 0)
                    }
                }) {
                    Text(text = "滚到顶部")
                }
            }

        }

    }

    @Composable
    fun AnnotatedClickableText(content:String) {
        val annotatedText = buildAnnotatedString {
            append("Click $content ")

            // We attach this *URL* annotation to the following content
            // until `pop()` is called
            pushStringAnnotation(tag = "URL",
                annotation = "https://developer.android.com")
            withStyle(style = SpanStyle(color = Color.Blue,
                fontWeight = FontWeight.Bold)
            ) {
                append("here")
            }

            pop()
        }

        ClickableText(
            text = annotatedText,
            onClick = { offset ->
                // We check if there is an *URL* annotation attached to the text
                // at the clicked position
                annotatedText.getStringAnnotations(tag = "URL", start = offset,
                    end = offset)
                    .firstOrNull()?.let { annotation ->
                        // If yes, we log its value
                        Log.d("Clicked URL", annotation.item)
                    }
            }
        )
    }
    // code 5
    @Composable
    fun CustomLayoutDemo() {
        Row(
            Modifier
                .background(Color(0xFF00FF00))
                .fillMaxWidth()
        ) {
            Text(
                text = "我是栗子1,我内部的布局未居中因为我外部设置了fillMaxWidth",
                modifier = Modifier
                    .firstBaselineToTop(60.dp)
                    .background(Color(0xFFB88076)),
                fontSize = 6.sp
            )

            Spacer(modifier = Modifier.width(20.dp))

            Text(
                text = "我是栗子2",
                modifier = Modifier
                    .firstBaselineToTop(60.dp)
                    .background(Color(0xFFB88076)),
                fontSize = 15.sp
            )

            Spacer(modifier = Modifier.width(20.dp))

            Text(
                text = "我是栗子3",
                modifier = Modifier
                    .firstBaselineToTop(60.dp)
                    .background(Color(0xFFB88076)),
                fontSize = 30.sp
            )
        }
    }

    @Composable
    fun NoCustomLayoutDemo() {
        Row(
            Modifier
                .background(Color(0xFF7684B8))
        ) {
            Text(
                text = "我是栗子1",
                modifier = Modifier
                    .padding(top = 60.dp)
                    .background(Color(0xFFB88076)),
                fontSize = 20.sp
            )

            Spacer(modifier = Modifier.width(20.dp))

            Text(
                text = "我是栗子2",
                modifier = Modifier
                    .padding(top = 60.dp)
                    .background(Color(0xFFB88076)),
                fontSize = 15.sp
            )

            Spacer(modifier = Modifier.width(20.dp))

            Text(
                text = "我是栗子3",
                modifier = Modifier
                    .padding(top = 60.dp)
                    .background(Color(0xFFB88076)),
                fontSize = 30.sp
            )
        }
    }

    // code 16
    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun Chip(
        modifier: Modifier = Modifier, text: String
    ) {
        Card(
            modifier = modifier,
            border = BorderStroke(color = Color.Magenta, width = Dp.Hairline),
            shape = RoundedCornerShape(8.dp)
        ) {
            Row(
                modifier = Modifier.padding(start = 8.dp, top = 4.dp, end = 8.dp, bottom = 4.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Box(
                    modifier = Modifier
                        .size(16.dp, 16.dp)
                        .background(color = Color(0xF652856D)),
                )
                Spacer(Modifier.width(4.dp))
                Text(text = text)
            }
        }
    }


    // code 3
    private fun Modifier.firstBaselineToTop(
        firstBaselineToTop: Dp
    ) = this.then(
        layout { measurable, constraints ->

            val placeable = measurable.measure(constraints)//文本的实际高度
            // 检查这个 Composable 组件是否存在 FirstBaseline
            check(placeable[FirstBaseline] != AlignmentLine.Unspecified)
            // 存在的情况下，获取 FirstBaseline 离 Composable 组件顶部的距离
            val firstBaseline = placeable[FirstBaseline]
            // 计算 Y 轴方向上 Composable 组件的放置位置
            val placeableY = firstBaselineToTop.roundToPx() - firstBaseline
            // 文本的实际高度+文本高度距离控件顶部的距离 ---计算得出此 Composable 组件真正的 height 值
            val height = placeable.height + placeableY
            layout(placeable.width, height) {
                placeable.placeRelative(0, placeableY)
            }
        }
    )


    // 横向瀑布流自定义 layout
    @Composable
    fun StaggeredGrid(
        modifier: Modifier = Modifier,
        rows: Int = 3,  // 自定义的参数，控制展示的行数，默认为 3行
        content: @Composable () -> Unit
    ) {
        Layout(
            modifier = modifier,
            content = content
        ) { measurables, constraints ->
            // 用于记录每一横行的宽度信息
            val rowWidths = IntArray(rows) { 0 }
            // 用于记录每一横行的高度信息
            val rowHeights = IntArray(rows) { 0 }
            // 测量每个 child 尺寸，获得每个 child 的 Placeable 对象
            val placeables = measurables.mapIndexed { index, measurable ->
                // 标准流程：测量每个 child 尺寸，获得 placeable
                val placeable = measurable.measure(constraints)
                // 根据序号给每个 child 分组，记录每一个横行的宽高信息
                val row = index % rows
                rowWidths[row] += placeable.width
                rowHeights[row] = max(rowHeights[row], placeable.height)
                placeable    // 这句别忘了，返回每个 child 的placeable
            }

            // 自定义 Layout 的宽度取所有行中宽度最大值
            val width = rowWidths.maxOrNull()
                ?.coerceIn(constraints.minWidth.rangeTo(constraints.maxWidth))
                ?: constraints.minWidth
            // 自定义 Layout 的高度当然为所有行高度之和
            val height = rowHeights.sumOf { it }
                .coerceIn(constraints.minHeight.rangeTo(constraints.maxHeight))
            // 计算出每一行的元素在 Y轴 上的摆放位置
            val rowY = IntArray(rows) { 0 }
            for (i in 1 until rows) {
                rowY[i] = rowY[i - 1] + rowHeights[i - 1]
            }

            // 设置 自定义 Layout 的宽高
            layout(width, height) {
                // 摆放每个 child
                val rowX = IntArray(rows) { 0 }  // child 在 X 轴的位置
                placeables.forEachIndexed { index, placeable ->
                    val row = index % rows
                    placeable.placeRelative(
                        rowX[row],
                        rowY[row]
                    )
                    rowX[row] += placeable.width
                }
            }
        }
    }

    class ColumnLayoutBean {
        var columnArray: ArrayList<ItemHeight> = ArrayList<ItemHeight>()
        var allHeight: Int = 0 //每一列的总高度
    }

    class ItemHeight {
        //原始下标
        var originIndex: Int = 0

        //child的高度
        var height: Int = 0

        //当前控件需要放置的Y轴位置
        var lastAllHeight: Int = 0

        //位于哪一列
        var column: Int = 0
    }

    @Composable
    fun CustomVerticalStaggeredGrid(
        modifier: Modifier = Modifier,
        column: Int = 3,  // 自定义的参数，控制展示的行数，默认为 2列
        content: @Composable () -> Unit
    ) {
        Layout(
            modifier = modifier,
            content = content
        ) { measurables, constraints ->
            Log.d("tgw", "CustomVerticalStaggeredGridmaxWidth:${constraints.maxWidth} ")
            Log.d("tgw", "CustomVerticalStaggeredGridminWidth:${constraints.minWidth} ")
            Log.d("tgw", "CustomVerticalStaggeredGrid maxHeight:${constraints.maxHeight} ")
            Log.d("tgw", "CustomVerticalStaggeredGrid minHeight:${constraints.minHeight} ")
            val columnHeights = Array<ColumnLayoutBean>(column) { ColumnLayoutBean() }
            //存储所有的item项
            var columnArray: ArrayList<ItemHeight> = ArrayList<ItemHeight>()
            //存储每一列的高度总和
            val columnHeightArray = IntArray(column) { 0 }


            // 测量每个 child 尺寸，获得每个 child 的 Placeable 对象
            val placeables = measurables.mapIndexed { index, measurable ->

                // 标准流程：测量每个 child 尺寸，获得 placeable,约束宽度，最大为控件的宽度除以列
                val placeable =
                    measurable.measure(constraints.copy(maxWidth = constraints.maxWidth / column))

                if (index < column) {//初始化列，先占满坑位
                    columnHeights[index % column].allHeight = placeable.height

                    val item = ItemHeight().apply {
                        this.originIndex = index
                        this.height = placeable.height
                        this.column = index % column
                        this.lastAllHeight = 0
                    }
                    columnHeights[index % column].columnArray.add(item)
                    columnArray.add(item)
                    columnHeightArray[index % column] = placeable.height

                } else {
                    // 取出高度最小的列，添加
                    val minIndex = columnHeightArray.indices.minBy { columnHeightArray[it] }
                    columnHeights[minIndex].allHeight += placeable.height
                    columnHeightArray[minIndex] = columnHeights[minIndex].allHeight
                    //获取当前item的开始时Y轴的放置位置
                    var lastHeight = 0
                    columnArray.filter { it.column == minIndex }.forEach {
                        lastHeight += it.height
                    }
                    val item = ItemHeight().apply {
                        this.originIndex = index
                        this.height = placeable.height
                        this.column = minIndex
                        this.lastAllHeight = lastHeight
                    }
                    columnHeights[minIndex].columnArray.add(item)
                    columnArray.add(item)
                }
                placeable    // 这句别忘了，返回每个 child 的placeable
            }

            // 取出最大列的高度
            val height = columnHeightArray.max()

            // 设置 自定义 Layout 的宽高
            layout(constraints.maxWidth, height) {
                // 摆放每个 child
                placeables.forEachIndexed { index, placeable ->
                    val currentColumn = columnArray[index].column
                    val x = (constraints.maxWidth / column * currentColumn).toInt()

                    placeable.placeRelative(
                        x,
                        columnArray[index].lastAllHeight
                    )
                }
            }
        }
    }


    /**
     *计算布局的子item高度,无用
     */
    @Composable
    fun ComputeVerticalHeight(
        modifier: Modifier = Modifier,
        column: Int = 3,  // 自定义的参数，控制展示的行数，默认为 2列
        content: @Composable () -> Unit
    ) {
        Layout(
            modifier = modifier,
            content = content
        ) { measurables, constraints ->
            Log.d("tgw", "CustomVerticalStaggeredGridmaxWidth:${constraints.maxWidth} ")
            Log.d("tgw", "CustomVerticalStaggeredGridminWidth:${constraints.minWidth} ")
            Log.d("tgw", "CustomVerticalStaggeredGrid maxHeight:${constraints.maxHeight} ")
            Log.d("tgw", "CustomVerticalStaggeredGrid minHeight:${constraints.minHeight} ")
            val columnHeights = Array<ColumnLayoutBean>(column) { ColumnLayoutBean() }
            //存储所有的item项
            var columnArray: ArrayList<ItemHeight> = ArrayList<ItemHeight>()
            //存储每一列的高度总和
            val columnHeightArray = IntArray(column) { 0 }


            // 测量每个 child 尺寸，获得每个 child 的 Placeable 对象
            val placeables = measurables.mapIndexed { index, measurable ->
                // 标准流程：测量每个 child 尺寸，获得 placeable,约束宽度，最大为控件的宽度除以列
                val placeable =
                    measurable.measure(constraints.copy(maxWidth = constraints.maxWidth / column))
                Log.d("tgw", "ComputeVerticalHeight:${placeable.height} ")

                if (index < column) {//初始化列，先占满坑位
                    columnHeights[index % column].allHeight = placeable.height

                    val item = ItemHeight().apply {
                        this.originIndex = index
                        this.height = placeable.height
                        this.column = index % column
                        this.lastAllHeight = 0
                    }
                    columnHeights[index % column].columnArray.add(item)
                    columnArray.add(item)
                    columnHeightArray[index % column] = placeable.height

                } else {
                    // 取出高度最小的列，添加
                    val minIndex = columnHeightArray.indices.minBy { columnHeightArray[it] }
                    columnHeights[minIndex].allHeight += placeable.height
                    columnHeightArray[minIndex] = columnHeights[minIndex].allHeight
                    //获取当前item的开始时Y轴的放置位置
                    var lastHeight = 0
                    columnArray.filter { it.column == minIndex }.forEach {
                        lastHeight += it.height
                    }
                    val item = ItemHeight().apply {
                        this.originIndex = index
                        this.height = placeable.height
                        this.column = minIndex
                        this.lastAllHeight = lastHeight
                    }
                    columnHeights[minIndex].columnArray.add(item)
                    columnArray.add(item)
                }
                placeable    // 这句别忘了，返回每个 child 的placeable
            }

            // 取出最大列的高度
            val height = columnHeightArray.max()


            // 设置 自定义 Layout 的宽高
            layout(constraints.maxWidth, height) {
                // 摆放每个 child
                placeables.forEachIndexed { index, placeable ->
                    val currentColumn = columnArray[index].column
                    val x = (constraints.maxWidth / column * currentColumn).toInt()

                    placeable.placeRelative(
                        0,
                        0
                    )
                }
            }
        }
    }


    @Composable
    fun CustomIntrinsicRow(modifier: Modifier, content: @Composable () -> Unit) {
        Layout(
            content = content,
            modifier = modifier,
            measurePolicy = object : MeasurePolicy {
                override fun MeasureScope.measure(
                    measurables: List<Measurable>,
                    constraints: Constraints
                ): MeasureResult {

                    var devideConstraints = constraints.copy(minWidth = 0)
                    var mainPlaceables = measurables.filter {
                        it.layoutId == "main"
                    }.map {
                        it.measure(constraints)
                    }
                    var devidePlaceable =
                        measurables.first { it.layoutId == "devider" }.measure(devideConstraints)
                    var midPos = constraints.maxWidth / 2
                    return layout(constraints.maxWidth, constraints.maxHeight) {
                        mainPlaceables.forEach {
                            it.placeRelative(0, 0)
                        }
                        devidePlaceable.placeRelative(midPos, 0)
                    }
                }

                override fun IntrinsicMeasureScope.minIntrinsicHeight(
                    measurables: List<IntrinsicMeasurable>,
                    width: Int
                ): Int {
                    var maxHeight = 0
                    measurables.forEach {
                        //当前it.maxIntrinsicHeight(width)小于maxHeight
                        maxHeight = it.maxIntrinsicHeight(width).coerceAtLeast(maxHeight)
                    }
                    return maxHeight
                }
            }
        )
    }


    @Composable
    fun StaggeredGrid1(
        items: List<String>,
        numColumns: Int,
        modifier: Modifier = Modifier
    ) {
        val rows = items.chunked(numColumns)
        LazyColumn(modifier) {
            items(rows.size) { index ->
                Row(Modifier.fillMaxWidth()) {
                    val row = rows[index]
                    row.forEach { item ->
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .padding(4.dp)
                        ) {
                            // 渲染每个项的内容和样式
                            Text(text = item)

                        }
                    }
                }
            }
        }
    }

    @Composable
    fun ColumnStaggeredGrid(products: List<String>) {
        Text(text = "LazyVerticalGrid 布局", modifier = Modifier.background(Color(0xFFC56565)))
//        LazyColumn(
//            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
//            modifier = Modifier.fillMaxWidth()
//        ) {
//            items(products.size) { index ->
//                Text(text = products[index])
//            }
//        }
//        Text(text = "LazyVerticalGrid 布局", modifier = Modifier.background(Color(0xFFC56565)))
//        LazyVerticalGrid(
//            columns = GridCells.Fixed(2),
//            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
//            modifier = Modifier.fillMaxWidth()
//        ) {
//            items(products.size) { index ->
//                Text(text = products[index])
//            }
//        }
        val height = remember {
            mutableStateOf(500.dp)
        }

        val heightCount = rememberSaveable( ) {
            mutableStateOf(0)
        }


        DisposableEffect(true){

            onDispose {
//                heightCount.value = 0
            }
        }

        var allHeight = remember {
            0.dp
        }
        Text(text = "LazyHorizontalGrid 布局", modifier = Modifier.background(Color(0xFFC56565)))
        LazyHorizontalGrid(
            rows = GridCells.Fixed(2),
//            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
            modifier = Modifier
                .height(height.value)
                .onSizeChanged {

                }
                .background(Color(0xFF4BD341))
                .fillMaxWidth()
//                .layout { measurable, constraints ->
//                    val placeable = measurable.measure(constraints)
//                    Log.d(
//                        "tgw2",
//                        "ColumnStaggeredGrid: height:${placeable.height}---width:${placeable.width}"
//                    )
//                    layout(placeable.width, placeable.height) {
//                        placeable.placeRelative(0, 0)
//                    }
//                }
        ) {

            itemsIndexed(products) { index, product ->
//                Log.d(
//                    "tgw3--Text",
//                    "index:$index ColumnStaggeredGrid: height:${ measureItemHeight(product)}"
//                )

                Text(text = product, modifier = Modifier
                    .wrapContentHeight()
                    .layout { measurable, constraints ->
                        val placeable = measurable.measure(constraints)
                        Log.d(
                            "tgw2--Text",
                            "index:$index ColumnStaggeredGrid: height:${placeable.height}---width:${placeable.width}"
                        )
                        if (heightCount.value == 0) {
                            height.value = placeable.height.toDp()
                            heightCount.value = 1
                        }
                        if (heightCount.value == 1) {
                            height.value += placeable.height.toDp()
                            heightCount.value = 2
                        }
//                        if (heightCount.value < 2) { //会造成多次刷新
//                            allHeight = allHeight + placeable.height.toDp()
//
////
//                            Log.d(
//                                "tgw2--grideHeight",
//                                "index ${index}ColumnStaggeredGrid: height:${placeable.height}---allHeight:$allHeight"
//                            )
//                            if (heightCount.value == 1) {
//                                height.value = allHeight
//                            }
//                            heightCount.value = heightCount.value + 1
//
//                        }


                        layout(placeable.width, placeable.height) {
                            placeable.placeRelative(0, 0)
                        }
                    }
                )
            }
        }

    }

    @Composable
    fun measureItemHeight(text: String): Int {

        // 存储Text的大小状态
        val textSizeState = remember { mutableStateOf(Size.Zero) }

        // 测量Text的大小
        Text(
            text = text,
            modifier = Modifier
                .onGloballyPositioned {
                    textSizeState.value = Size(it.size.width.toFloat(), it.size.height.toFloat())
                }
        )

        // 返回Text的高度作为item高度
        return textSizeState.value.height.toInt()
    }
    @Composable
    fun StaggeredProductItem(product: String, spanSize: Int) {
        Box(
            modifier = Modifier
                .padding(8.dp)
                .fillMaxWidth()
                .heightIn(min = 50.dp, max = 100.dp)
                .layout { measurable, constraints ->
                    val placeable = measurable.measure(constraints)
                    layout(placeable.width, placeable.height) {
                        placeable.placeRelative(0, 0)
                    }
                }
                .background(Color.Gray)
        ) {
            Text(
                text = product,
                modifier = Modifier.padding(16.dp),
                color = Color.White,
                fontSize = 16.sp
            )
        }
    }

    @Composable
    fun Placeable.PlacementScope.StaggeredVerticalGrid(
        modifier: Modifier = Modifier,
        rows: Int = 3,
        content: @Composable () -> Unit
    ) {

        // 使用 Layout 定义布局
        Layout(
            modifier = modifier,
            content = content
        ) { measurables, constraints ->

            // tracking height of each column
            val colHeights = IntArray(rows) { 0 }

            // Placeables to layout
            val placeables = measurables.map { measurable ->
                // Measure each item
                val placeable = measurable.measure(constraints)

                // Track the height of each column
                val minHeight = colHeights.min()
                val index = colHeights.indexOf(minHeight)

                // Position item at calculated x/y
                placeable.place(x = (index * placeable.width).toInt(), y = minHeight)

                // Record height
                colHeights[index] = minHeight + placeable.height
                placeable
            }

            // Set size of layout as big as it can
            layout(width = constraints.maxWidth, height = colHeights.max()) {
                // Draw all the placeables
                placeables.forEach { placeable ->
                    // Draw with item's own position/size
                    placeable.placeRelative(0, 0)
                }
            }
        }
    }


    @Composable
    fun StaggeredGrid2(
        items: List<String>,
        numColumns: Int,
        modifier: Modifier = Modifier
    ) {
        val rows = items.chunked(numColumns)
        LazyColumn(modifier) {
            items(rows.size) { rowIndex ->
                Row(Modifier.fillMaxWidth()) {
                    val row = rows[rowIndex]
                    val heights = remember { mutableStateListOf<Int>() }
                    row.forEachIndexed { index, item ->
                        val boxHeight = remember { mutableStateOf(0) }
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .padding(4.dp)
                                .height(IntrinsicSize.Min)
                                .onSizeChanged { size ->
                                    boxHeight.value = size.height
                                }// 设置项的高度为最小高度
                        ) {
                            // 渲染每个项的内容和样式
                            Text(
                                text = item,
                                modifier = Modifier.padding(16.dp),
                                color = Color.White,
                                fontSize = 16.sp
                            )
                        }
                        LaunchedEffect(Unit) {
                            // 计算每个项的高度，并保存到列表中
                            val height = boxHeight.value
                            heights.add(height)
                        }
                    }
//                    Spacer(Modifier.height(getMaxHeight(heights) - getItemHeight()))
                }
            }
        }
    }

    @Composable
    fun getMaxHeight(heights: List<Int>): Int {
        return heights.maxOrNull() ?: 0
    }


    @Preview(showBackground = true)
    @Composable
    fun DefaultPreview() {
        MyComposeLearingTheme {
            Greeting("Android")
        }
    }

}